<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class TransactionController extends Controller
{
    /**
     * 获取交易账单列表
     */
    public function index(Request $request): JsonResponse
    {
        try {
            // 获取租户ID
            $tenantId = $request->user()->tenant_id;
            
            Log::info('交易账单列表请求', [
                'tenant_id' => $tenantId,
                'params' => $request->all()
            ]);
            
            // 构建查询
            $query = Transaction::where('tenant_id', $tenantId);
            
            // 搜索条件
            if ($request->filled('transaction_id')) {
                $transactionId = trim($request->input('transaction_id'));
                $query->where(function($q) use ($transactionId) {
                    $q->where('transaction_number', 'like', "%{$transactionId}%")
                      ->orWhere('id', 'like', "%{$transactionId}%");
                });
            }
            
            if ($request->filled('type')) {
                $query->where('type', $request->input('type'));
            }
            
            if ($request->filled('sub_type')) {
                $query->where('sub_type', $request->input('sub_type'));
            }
            
            if ($request->filled('status')) {
                $query->where('status', $request->input('status'));
            }
            
            if ($request->filled('landing_company')) {
                $landingCompany = trim($request->input('landing_company'));
                $query->where('landing_company', 'like', "%{$landingCompany}%");
            }
            
            // 交易时间范围
            if ($request->filled('start_date') && $request->filled('end_date')) {
                $startDate = $request->input('start_date') . ' 00:00:00';
                $endDate = $request->input('end_date') . ' 23:59:59';
                $query->whereBetween('transaction_time', [$startDate, $endDate]);
            }
            
            // 排序
            $sortBy = $request->input('sort_by', 'transaction_time');
            $sortOrder = $request->input('sort_order', 'desc');
            $query->orderBy($sortBy, $sortOrder);
            
            // 分页
            $perPage = (int) $request->input('per_page', 15);
            $perPage = min($perPage, 100); // 限制每页最大100条
            
            $transactions = $query->paginate($perPage);
            
            // 处理数据
            $processedData = $transactions->getCollection()->map(function ($transaction) {
                return [
                    'id' => $transaction->id,
                    'transaction_id' => $transaction->transaction_id,
                    'transaction_number' => $transaction->transaction_number,
                    'tenant_id' => $transaction->tenant_id,
                    'type' => $transaction->type,
                    'type_display' => $transaction->type_display,
                    'sub_type' => $transaction->sub_type,
                    'sub_type_display' => $transaction->sub_type_display,
                    'amount' => $transaction->amount,
                    'balance_after' => $transaction->balance_after,
                    'landing_company' => $transaction->landing_company,
                    'status' => $transaction->status,
                    'status_display' => $transaction->status_display,
                    'summary' => $transaction->summary,
                    'description' => $transaction->description,
                    'transaction_time' => $transaction->transaction_time,
                    'created_at' => $transaction->created_at,
                    'updated_at' => $transaction->updated_at,
                    'processed_at' => $transaction->processed_at,
                    'created_by' => $transaction->created_by,
                    'processed_by' => $transaction->processed_by,
                ];
            });
            
            $result = [
                'data' => $processedData,
                'current_page' => $transactions->currentPage(),
                'per_page' => $transactions->perPage(),
                'total' => $transactions->total(),
                'last_page' => $transactions->lastPage(),
                'from' => $transactions->firstItem(),
                'to' => $transactions->lastItem(),
                'first_page_url' => $transactions->url(1),
                'last_page_url' => $transactions->url($transactions->lastPage()),
                'next_page_url' => $transactions->nextPageUrl(),
                'prev_page_url' => $transactions->previousPageUrl(),
                'path' => $transactions->path(),
                'links' => $transactions->linkCollection()->toArray()
            ];
            
            Log::info('交易账单列表查询成功', [
                'tenant_id' => $tenantId,
                'total' => $transactions->total(),
                'current_page' => $transactions->currentPage()
            ]);
            
            return response()->json([
                'code' => 0,
                'data' => $result,
                'message' => '获取交易账单列表成功'
            ]);
            
        } catch (\Exception $e) {
            Log::error('交易账单列表查询失败', [
                'tenant_id' => $request->attributes->get('tenant_id'),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '获取交易账单列表失败',
                'error' => [
                    'details' => $e->getMessage()
                ]
            ], 500);
        }
    }

    /**
     * 获取交易账单详情
     */
    public function show(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $transaction = Transaction::where('tenant_id', $tenantId)->where('id', $id)->first();
            
            if (!$transaction) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => '交易记录不存在或无权访问'
                ], 404);
            }
            
            return response()->json([
                'code' => 0,
                'data' => [
                    'id' => $transaction->id,
                    'transaction_id' => $transaction->transaction_id,
                    'transaction_number' => $transaction->transaction_number,
                    'tenant_id' => $transaction->tenant_id,
                    'type' => $transaction->type,
                    'type_display' => $transaction->type_display,
                    'sub_type' => $transaction->sub_type,
                    'sub_type_display' => $transaction->sub_type_display,
                    'amount' => $transaction->amount,
                    'balance_after' => $transaction->balance_after,
                    'landing_company' => $transaction->landing_company,
                    'status' => $transaction->status,
                    'status_display' => $transaction->status_display,
                    'summary' => $transaction->summary,
                    'description' => $transaction->description,
                    'metadata' => $transaction->metadata,
                    'transaction_time' => $transaction->transaction_time,
                    'created_at' => $transaction->created_at,
                    'updated_at' => $transaction->updated_at,
                    'processed_at' => $transaction->processed_at,
                    'created_by' => $transaction->created_by,
                    'processed_by' => $transaction->processed_by,
                ],
                'message' => '获取交易详情成功'
            ]);
            
        } catch (\Exception $e) {
            Log::error('获取交易详情失败', [
                'id' => $id,
                'tenant_id' => $request->attributes->get('tenant_id'),
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '获取交易详情失败'
            ], 500);
        }
    }

    /**
     * 获取子类型选项
     */
    public function getSubTypes(Request $request): JsonResponse
    {
        try {
            $type = $request->input('type');
            
            $subTypes = [];
            if ($type === 'income') {
                $subTypes = Transaction::getIncomeSubTypes();
            } elseif ($type === 'expense') {
                $subTypes = Transaction::getExpenseSubTypes();
            } else {
                $subTypes = array_merge(
                    Transaction::getIncomeSubTypes(),
                    Transaction::getExpenseSubTypes()
                );
            }
            
            // 转换为前端需要的格式
            $options = [];
            foreach ($subTypes as $value => $label) {
                $options[] = [
                    'value' => $value,
                    'label' => $label
                ];
            }
            
            return response()->json([
                'code' => 0,
                'data' => $options,
                'message' => '获取子类型选项成功'
            ]);
            
        } catch (\Exception $e) {
            Log::error('获取子类型选项失败', [
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'data' => [],
                'message' => '获取子类型选项失败'
            ], 500);
        }
    }

    /**
     * 导出交易账单数据为CSV
     */
    public function export(Request $request): JsonResponse
    {
        try {
            // 获取租户ID
            $tenantId = $request->user()->tenant_id;
            
            // 构建查询（与index方法相同的逻辑）
            $query = Transaction::where('tenant_id', $tenantId);
            
            // 应用搜索条件
            if ($request->filled('transaction_id')) {
                $transactionId = trim($request->input('transaction_id'));
                $query->where(function($q) use ($transactionId) {
                    $q->where('transaction_number', 'like', "%{$transactionId}%")
                      ->orWhere('id', 'like', "%{$transactionId}%");
                });
            }
            
            if ($request->filled('type')) {
                $query->where('type', $request->input('type'));
            }
            
            if ($request->filled('sub_type')) {
                $query->where('sub_type', $request->input('sub_type'));
            }
            
            if ($request->filled('status')) {
                $query->where('status', $request->input('status'));
            }
            
            if ($request->filled('landing_company')) {
                $landingCompany = trim($request->input('landing_company'));
                $query->where('landing_company', 'like', "%{$landingCompany}%");
            }
            
            if ($request->filled('start_date') && $request->filled('end_date')) {
                $startDate = $request->input('start_date') . ' 00:00:00';
                $endDate = $request->input('end_date') . ' 23:59:59';
                $query->whereBetween('transaction_time', [$startDate, $endDate]);
            }
            
            // 排序
            $query->orderBy('transaction_time', 'desc');
            
            // 获取所有数据（用于导出，不分页）
            $transactions = $query->get();
            
            Log::info('交易账单数据导出', [
                'tenant_id' => $tenantId,
                'count' => $transactions->count()
            ]);
            
            return response()->json([
                'code' => 0,
                'data' => [
                    'count' => $transactions->count(),
                    'export_url' => '/api/tenant/transactions/download-csv?' . http_build_query($request->all())
                ],
                'message' => '导出数据准备完成'
            ]);
            
        } catch (\Exception $e) {
            Log::error('交易账单数据导出失败', [
                'tenant_id' => $request->attributes->get('tenant_id'),
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '导出数据失败'
            ], 500);
        }
    }
}